//
//  CategoryViewController.swift
//  CompareBuying
//
//  Created by 唐先才 on 16/2/2.
//  Copyright © 2016年 唐先才. All rights reserved.
//

import UIKit

class CategoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {

    var tableView: UITableView?
    var collectionView: UICollectionView?
    var dataArray: NSMutableArray = []
    var parameters: NSDictionary?
    var titleArray: NSArray = []
    var parametersArray: NSArray = []
    var index: NSInteger?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        titleArray = ["有机生活","服饰鞋包", "日用百货","食品保健","母婴用品","个护美妆","家用电器", "电脑数码", "运动户外", "旅游度假","图书音像", "钟表首饰", "家居家装","玩模乐器","办公设备","汽车用品","其他分类"]
        parametersArray = [["parentUrl": "youjishenghuo"],
                           ["parentUrl": "fushixiebao"],
                           ["parentUrl": "riyongbaihuo"],
                           ["parentUrl": "shipinbaojian"],
                           ["parentUrl": "muyingyongpin"],
                           ["parentUrl": "gehumeizhuang"],
                           ["parentUrl": "jiayongdianqi"],
                           ["parentUrl": "diannaoshuma"],
                           ["parentUrl": "yundonghuwai"],
                           ["parentUrl": "lvyoudujia"],
                           ["parentUrl": "tushuyinxiang"],
                           ["parentUrl": "zhongbiaoshoushi"],
                           ["parentUrl": "jiajujiazhuang"],
                           ["parentUrl": "wanmoleqi"],
                           ["parentUrl": "bangongshebei"],
                           ["parentUrl": "qicheyongpin"],
                           ["parentUrl": "qitafenlei"],
                           ]
        index = 0
        self.createData()
        self.createUI()
    }
    
    func createData() {
        
        guard let index = index else {
            return
        }
        guard let dict = parametersArray[index] as? NSDictionary else {
            print("参数字典创建失败")
            return
        }
        parameters = dict
        let manager = AFHTTPRequestOperationManager()
        manager.POST("http://mws.biyabi.com/webservice.asmx/GetChildCatagoryListJson", parameters: parameters, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject?) -> Void in
            guard let array = responseObject as? [[String: AnyObject]] else {
                return
            }
            for dict in array {
                let model = TxcModel.modelWithDict(dict)
                self.dataArray.addObject(model)
            }
            guard let collectionView = self.collectionView else {
                return
            }
            collectionView.reloadData()
            }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
                print("-------\(error)-------")
        }
    }
    
    func createUI() {
        tableView = UITableView(frame: CGRect(x: 0, y: 0, width: WIDTH / 4, height: HEIGHT - 150))
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = UICollectionViewScrollDirection.Vertical
        collectionView = UICollectionView(frame: CGRect(x: WIDTH / 4, y: 0, width: CGFloat(3) * WIDTH / 4, height: HEIGHT), collectionViewLayout: layout)
        guard let tableView = tableView, collectionView = collectionView else {
            return
        }
        tableView.dataSource = self
        tableView.delegate = self
        tableView.showsVerticalScrollIndicator = false
        self.view.addSubview(tableView)
        collectionView.backgroundColor = UIColor.whiteColor()
        collectionView.dataSource = self
        collectionView.delegate = self
        self.view.addSubview(collectionView)
        let nib = UINib(nibName: "SearchCell", bundle: NSBundle.mainBundle())
        collectionView.registerNib(nib, forCellWithReuseIdentifier: "searchCell")
    }
    
    //mark --tableView
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titleArray.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("cell")
        if (cell == nil) {
            cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "cell")
        }
        if let cell1 = cell {
            guard let textLab = cell1.textLabel else {
               return cell1
            }
            guard let name = titleArray[indexPath.row] as? String else{
                return cell1
            }
            cell1.backgroundColor = UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 0.3)
            let backView = UIView()
            backView.backgroundColor = UIColor.whiteColor()
            cell1.selectedBackgroundView = backView
            textLab.text = name
            if WIDTH == 375 {
//                print("字体大小")
                textLab.font = UIFont.systemFontOfSize(13)
            } else {
                textLab.font = UIFont.systemFontOfSize(11)
            }
            textLab.textAlignment = NSTextAlignment.Center
            return cell1
        }
        guard let defaultCell = cell else {
            return UITableViewCell()
        }
        return defaultCell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        index = indexPath.row
        self.dataArray.removeAllObjects()
        self.createData()
    }
    
    //pragma mark - collectionView
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        if let searchCell = collectionView.dequeueReusableCellWithReuseIdentifier("searchCell", forIndexPath: indexPath) as? SearchCell {
            if self.dataArray.count > 0 {
                if let model = self.dataArray[indexPath.row] as? TxcModel {
                    searchCell.configCellWithModel(model)
                }
            }
            return searchCell
        }
        return UICollectionViewCell()
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        return CGSizeMake((collectionView.frame.size.width - 30) / 3, 120)
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(5, 5, 5, 5)
    }
}
